<template>
	<view class="flex-column justify-center align-center">
		<view class="text-black p_t25 p_b10">
			邀请您参与计分
		</view>
		<view class="">
			<uni-tag type="primary" @click="onJoin">立即加入</uni-tag>
		</view>
	</view>
</template>

<script>
	import Table from "@/api/Table.js"
	import {
		toast,
		toastComfirm,
	} from "@/utils/helpers.js"
	import {
		mapState,
		mapGetters,
	} from "vuex"
	export default {
		computed: {
			...mapState("user", [
				'userInfo',
			]),
			...mapGetters("user", [
				"isEmptyUserInfo"
			])
		},
		data() {
			return {
				id: 0,
				promise: null,
				group: [],
				members: [],
			}
		},
		onLoad(options) {
			this.id = options.id;
			this.getInfo();
			this.$store.dispatch("user/getToken")
		},
		methods: {
			async onJoin() {
				try {
					if (this.isEmptyUserInfo) { // 用户未完善信息(调起微信信息授权)
						await this.$store.dispatch("user/updateUserInfoByWx")
						if (this.isEmptyUserInfo) { // 用户未完善信息
							throw new Error("请先完善用户信息")
						}
					} else {
						const canConfirm = await toastComfirm("确定加入吗？")
						if (!canConfirm) {
							return;
						}
					}

					await this.tryJoin();
				} catch (e) {
					toast(e.message)
				}
			},
			async tryJoin() {
				try {
					await this.getInfo();
					const uid = this.userInfo.id;
					if (uid && this.members.find(v => v.user_id === uid)) { // 当前用户已经存在了
						this.redirectToInfoPage();
						return;
					}
					await Table.join(this.id);
					toast("加入成功")
					this.redirectToInfoPage();
				} catch (e) {
					this.promise = null;
					toast(e.message)
				}
			},
			redirectToInfoPage() {
				uni.redirectTo({
					url: `/pages/list/info?id=${this.id}`
				});
			},
			// 获取计划详情
			async getInfo() {
				try {
					if (this.members.length || this.group.length) {
						return;
					}
					if (!this.promise || !(this.promise instanceof Promise)) {
						this.promise = Table.info(this.id);
					}
					const data = await this.promise;
					this.promise = null;
					this.members = data[1] || data.info || [];
					this.group = data['group'];
				} catch (e) {
					this.promise = null;
					toast(e.message)
				}
			},
		}
	}
</script>

<style>
</style>
